<?php 


class CtripModel extends Model {

    const TBL_CITY = 'city';

    public function addCity($data)
    {
        $this->_db->where('name', $data['name']);
        if (!$this->_db->getOne(SELF::TBL_CITY)){
            if ( ! $id = $this->_db->insert(self::TBL_CITY, $data) ) {
                 error_log('insert city data error '. $this->_db->getLastError());
                 exit();
            }
        }
        return TRUE;
    }

    public function getZone($id=FALSE)
    {
        if ($id) {
            $this->_db->where('id', $id);
            $data = $this->_db->getOne(SELF::TBL_ZONE);
        }
        else
        {
            $data = $this->_db->get(SELF::TBL_ZONE, null);
        }
        if(!$data) {
            return FALSE;
        } 
        return $data;

    }

    public function getMall($id=FALSE)
    {
        if ($id) {
            $this->_db->where('id', $id);
            $data = $this->_db->getOne(SELF::TBL_MALL);
        }
        else
        {
            $data = $this->_db->get(SELF::TBL_MALL, null);
        }
        if(!$data) {
            return FALSE;
        } 
        return $data;

    }


    public function addMall($data)
    {
        $this->_db->where('name', $data['name']);
        $this->_db->where('city_id', $data['city_id']);
        $this->_db->where('zone_id', $data['zone_id']);
        if (!$this->_db->getOne(SELF::TBL_MALL)){
            if ( ! $id = $this->_db->insert(self::TBL_MALL, $data) ) {
                 error_log('insert mall data error '. $this->_db->getLastError());
                 exit();
            }
        }
        return TRUE;

    }

    public function addMenu($data)
    {
        $this->_db->where('menu_name', $data['menu_name']);
        $this->_db->where('city_id', $data['city_id']);
        $this->_db->where('zone_id', $data['zone_id']);
        $this->_db->where('mall_id', $data['mall_id']);
        $this->_db->where('menu_price', $data['menu_price']);


        if (!$this->_db->getOne(SELF::TBL_MENU)){
            if ( ! $id = $this->_db->insert(self::TBL_MENU, $data) ) {
                 error_log('insert mall data error '. $this->_db->getLastError());
                 exit();
            }
        }


        return TRUE;

    }

    public function scrapCount($mallId)
    {
        $this->_db->where('id', $mallId);
        $data = [
            'scrap_count' => $this->_db->inc(1)
        ]; 
        if(! $this->_db->update(SELF::TBL_MALL, $data) ) 
        {
             error_log('update menu data error '. $this->_db->getLastError());
             exit();
        }
        return TRUE;
    }

}
